package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.*;

/**
 * @ProjectName: qingcheng_parent
 * @ClassName: ItemController
 * @Time: 2019/7/5
 * @Author: zhou24
 * @Description:
 * @Experience:
 */
@RestController
@RequestMapping("/item")
public class ItemController {
    @Reference
    private SpuService spuService;
    @Reference
    private CategoryService categoryService;

    /**
     * 模板引擎
     */
    @Autowired
    private TemplateEngine templateEngine;

    //读取配置文件：存导出的html地址
    @Value("${pagePath}")
    private String pagePath;

    @GetMapping("/createPage")
    public void createPage(String spuId) {
        Goods goods = spuService.findGoodsById(spuId);
        Spu spu = goods.getSpu();
        List<Sku> skuList = goods.getSkuList();
        //商品分类
        ArrayList<String> categoryNameList = new ArrayList<>();
        categoryNameList.add(categoryService.findById(spu.getCategory1Id()).getName());
        categoryNameList.add(categoryService.findById(spu.getCategory2Id()).getName());
        categoryNameList.add(categoryService.findById(spu.getCategory3Id()).getName());
        Map paraItems=   JSON.parseObject( spu.getParaItems());//参数列表

        //生成SKU地址列表
        Map<String,String> urlMap = new HashMap();
        for (Sku sku : skuList) {
            if("1".equals(sku.getStatus())){
                //依据sku对应的spec生成SKU地址列表的（选中规格的）key；因为map无需，为保证key顺序唯一确定，做排序处理
                String specJson = JSON.toJSONString(JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField);
                urlMap.put(specJson, sku.getId() + ".html");
            }
        }

        for (Sku sku : skuList) {
            // 1.上下文
            Context context = new Context();
            Map<String, Object> dataModel = new HashMap();
            //创建数据模型
            //基本信息
            dataModel.put("spu", spu);
            dataModel.put("sku", sku);
            dataModel.put("categoryNameList", categoryNameList);//商品分类面包屑
            dataModel.put("skuImages", sku.getImages().split(","));//SKU图片列表
            dataModel.put("spuImages", spu.getImages().split(","));//SPU图片列表

            dataModel.put("paraItems",paraItems);//参数列表
            Map<String,String> specItems = (Map)JSON.parseObject(sku.getSpec());//规格列表  当前sku
            dataModel.put("specItems", specItems);//规格列表

            //循环插入规格选择面板(要放在大循环里面，每次要重新刷新specMap)
            Map<String, List> specMap = (Map) JSONObject.parseObject(spu.getSpecItems());
            for (String key : specMap.keySet()) {
                List<String> listSpecs = specMap.get(key);
                ArrayList<Map> mapList = new ArrayList<>();
                for (String value : listSpecs) {
                    Map map = new HashMap<>();
                    map.put("option", value);
                    if ( value.equals(specItems.get(key))) {
                        map.put("checked", "true");
                    } else {
                        map.put("checked", "false");
                    }
//                   商品详细页地址  (添加以下代码)
                    Map<String,String> spec = (Map) JSON.parseObject(sku.getSpec());//当前SKU规格
                    spec.put(key, value);
                    String specJson = JSON.toJSONString(spec, SerializerFeature.MapSortField);
                    map.put("url", urlMap.get(specJson));
                    mapList.add(map);
                }
                specMap.put(key, mapList);
            }
            //JSON.toJSONString(newMap)将“=”转“：”
            //JSON.parseObject(JSON.toJSONString(newMap))将字符串转json对象
//            dataModel.put("specMap", JSON.parseObject(JSON.toJSONString(specMap)));//规格选项列表
            dataModel.put("specMap",specMap);

            //注入model
            context.setVariables(dataModel);
            // 2.准备文件
            File dir = new File(pagePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File dest = new File(dir, sku.getId() + ".html");
            // 3.生成页面
            try {
                PrintWriter writer = new PrintWriter(dest, "UTF-8");
                //输出页面
                templateEngine.process("item", context, writer);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
